package com.erpanderp.wam.ac.view.reimbursement;
	
	
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
	
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.swing.SwingWorker;

import org.primefaces.context.RequestContext;
	
import com.erpanderp.wam.ac.model.entity.reimbursement.Currency;
import com.erpanderp.wam.ac.model.entity.reimbursement.MiscExpense;
import com.erpanderp.wam.ac.model.entity.reimbursement.MiscExpenseDetails;
import com.erpanderp.wam.ac.model.service.reimbursement.MiscReimbursementDAO;
import com.erpanderp.wam.adm.model.entity.CustomLookup;
import com.erpanderp.wam.adm.model.entity.LookupValue;
import com.erpanderp.wam.adm.model.service.CustomLookupDAO;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;
	
	
@ViewScoped
@ManagedBean
public class ApproveReimbursementBean implements Serializable{

		private static final long serialVersionUID = 1L;
		private TimeZone timeZone = TimeZone.getDefault();
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
		private MiscExpense miscExpense = new MiscExpense();
		private MiscReimbursementDAO miscReimbursementDAO = new MiscReimbursementDAO();
		private Employee employee = new Employee();
		private EmployeeDAO employeeDAO = new EmployeeDAO();
		private MiscExpenseDetails miscExpenseDetails = new MiscExpenseDetails();
		private List<MiscExpenseDetails> miscExpensesDetails = new ArrayList<MiscExpenseDetails>();
		EmailUtil emailUtil;
		private Employee accountant = new Employee();
		String EMAIL_MESSAGE;
		boolean FORM_VALID;
		private EmployeeAndReportingDAO employeeAndReportingDAO = new EmployeeAndReportingDAO();
		private float balance;
		
		private List<Currency> Currencies = new ArrayList<Currency>();
		private List<LookupValue> lookUpValuesList = new ArrayList<LookupValue>();
		private CustomLookup customLookUp = new CustomLookup();
		private CustomLookupDAO customLookupDAO = new CustomLookupDAO();
		private Map<String,String> currencyMap = new HashMap<String, String>();
		
		
		public ApproveReimbursementBean(){
			System.out.println("IN APPROVE REIMBURSEMENT");
			accountant = employeeAndReportingDAO.getAccountantByModule(CommonLookup.DESIGNATION_ACCOUNTS);
			String miscExpenseCode = request.getParameter("miscCode");  
			System.out.println("MISCCODE IS "+miscExpenseCode);
			if(miscExpenseCode != null && !miscExpenseCode.equals("")){
				miscExpense = miscReimbursementDAO.getMiscExpense(miscExpenseCode);
				//miscExpense.setApprovedCurrency(miscExpense.getAdvanceTakenCurrency());
				//miscExpense.setBalancePayableCurrency(miscExpense.getAdvanceTakenCurrency());
				
				System.out.println("MISC DETAILS SIZE IS "+miscExpensesDetails.size());
				if(miscExpense == null){
					System.out.println("MISC EXPENSE IS NULL");
					ValidationUtil.gotoLoginPage();
				}else if(miscExpense.getExpenseStatus().equals(CommonLookup.MISC_INPROCESS_STATUS)){
					miscExpensesDetails.addAll(miscExpense.getMiscExpensesDetails());
					System.out.println("IN PROCES ");
				}			
			}else{
				ValidationUtil.gotoLoginPage();
			}
			
			customLookUp = customLookupDAO
					.getCustomLookUp(CommonLookup.CURRENCY_CUSTOM_LOOKUP);
			lookUpValuesList = customLookupDAO.getLookupValuesList(customLookUp
					.getCustomLookId());
			
			if(miscExpense.getAdvanceTakenCurrency() ==null || miscExpense.getAdvanceTakenCurrency().equals("")){
				for(LookupValue lookUpValue : lookUpValuesList){
					currencyMap.put(lookUpValue.getLookupName(), lookUpValue.getLookupValue());
				}
				miscExpense.setAdvanceTakenCurrency(miscExpense.getApprovedCurrency());
				miscExpense.setBalancePayableCurrency(miscExpense.getApprovedCurrency());
			}else{
				currencyMap.put(miscExpense.getAdvanceTakenCurrency(), miscExpense.getAdvanceTakenCurrency());
				miscExpense.setApprovedCurrency(miscExpense.getAdvanceTakenCurrency());
				miscExpense.setBalancePayableCurrency(miscExpense.getAdvanceTakenCurrency());
			}

			totalAmountandCurrencyList();
		}
		
		public void confirmationAction(ActionEvent e){
			 validate();
	 		
	 		if(FORM_VALID){
				RequestContext.getCurrentInstance().execute("confirmation.show();");
			}else{
				RequestContext.getCurrentInstance().execute("confirmation.hide();");
			}
	    }
		
		public void confirmationRejectAction(ActionEvent e){
			validateReject();
	 		
	 		if(FORM_VALID){
				RequestContext.getCurrentInstance().execute("confirmationReject.show();");
			}else{
				RequestContext.getCurrentInstance().execute("confirmationReject.hide();");
			}
	    }	
		// Total Amount LIST & Currency
		public void totalAmountandCurrencyList() {
			for (LookupValue currency : lookUpValuesList) {
				for (MiscExpenseDetails miscExpenseDetails : miscExpensesDetails) {
					if (miscExpenseDetails.getCurrency().equals(
							currency.getLookupValue())) {
						// MATCHED = true;
						boolean ADDED = false;
						for (Currency cur : Currencies) {
							if (currency.getLookupValue().equals(cur.getCurrency())) {
								ADDED = true;
								// change the value
								cur.setAmount(cur.getAmount()
										+ miscExpenseDetails.getAmount());
								break;
							}
						}
						if (!ADDED) {
							// create new currentcy and add to the list
							Currency currencyObj = new Currency();
							currencyObj.setAmount(miscExpenseDetails
									.getAmount());
							currencyObj.setCurrency(miscExpenseDetails
									.getCurrency());
							Currencies.add(currencyObj);
						}
						// break;
					}
				}
			}
		}
	
		// CURRENCY CHANGE LISTENER
		public void currencyChangeListener(AjaxBehaviorEvent e) {
			System.out.println("INSIDE CURRENCY CHANGE LISTENER");
			miscExpense.setAdvanceTakenCurrency(miscExpense.getApprovedCurrency());
			miscExpense.setBalancePayableCurrency(miscExpense.getApprovedCurrency());
		}
		public void getBalancePay(AjaxBehaviorEvent e) {
			
			float approvalTotal = miscExpense.getApprovedAmount();
			System.out.println("approvalTotal ::::::::" + approvalTotal);

			float balanceAmt = approvalTotal - miscExpense.getAdvanceTakenAmount();

			System.out.println("balanceAmt ::::::::" + balanceAmt);

			miscExpense.setBalancepayableAmount(balanceAmt);

		}
		public void approveMiscExpense(){
			System.out.println("IN APPROVE");
			 validate();
			 if(FORM_VALID){
				
					 System.out.println("EXPENSES SIZE = "+miscExpensesDetails.size());
					
					
					 miscExpense.setExpenseStatus(CommonLookup.MISC_APPROVED_STATUS);
					
					 miscReimbursementDAO.updateMiscExpenseForm(miscExpense);
					 FacesMessage msg = new FacesMessage("Miscellaneous reimbursement form approved successfully.", null);  
				     FacesContext.getCurrentInstance().addMessage(null, msg);
				    // miscExpense = new MiscExpense();
				     
				        Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
						String domainName = context.getInitParameter("domainName");
						//String[] to = {"ramakrishna.t@erpanderp.com"};
						//String[] cc = {"ramakrishna.t@erpanderp.com"};
						emailUtil = new EmailUtil();
						if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){
							String[] to = {miscExpense.getEmployee().getEmail()};//TO DO
							String[] cc = {accountant.getEmail()};
							emailUtil.setRecieverAddresses(to);
							emailUtil.setCCAddresses(cc);
						}else{
							String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
							emailUtil.setRecieverAddresses(to);
							emailUtil.setCCAddresses(to);
						}	
						
						String requestURL = "ac/reimbursement/viewmiscreimbursement.html?miscExpenseCode=" + miscExpense.getMiscExpenseCode();
						String privateLink = "http://" + hostsMap.get(CommonLookup.PRIVATEHOST) + "/" + domainName + "/" + requestURL;
						String publicLink = "http://" + hostsMap.get(CommonLookup.PUBLICHOST) + "/"	+ domainName + "/" + requestURL;
						String messageString = "Dear "+miscExpense.getEmployee().getFirstName()+" "+miscExpense.getEmployee().getLastName()+",<br /><br />"+  
											
										        "Your Miscellaneous Expense Request Form " + miscExpense.getMiscExpenseCode() + " is Approved. <br/><br/>" +
										       
										        "<b>Approver comments : </b>"+miscExpense.getApprovalComment() +"<br /><br/>"+	
										        
												"<a style='color:#FF9933;font-weight: bold;' href=\""+ privateLink + "\">"+ "Please click here to View/Print misc. expense request form"
												+ "</a /><br />" + "(Employees who are in Hyderabad office)"
												+ "<br /><br />"
												+ "<a style='color:#FF9933;font-weight: bold;' href=\""
												+ publicLink + "\">"
												+ "Please click here to View/Print misc. expense request form"
												+ "</a /><br />" + "(out side Hyderabad office)"
												+ "<br /><br />" +
										        
										     
												"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;;
						
						emailUtil.setMessage(messageString);
						emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
						emailUtil.setSubject("WAM - "+miscExpense.getEmployee().getFirstName()+ " "+miscExpense.getEmployee().getLastName()+" Misc. Expense Request (" + miscExpense.getMiscExpenseCode() + ") is Approved");
	
						SwingWorker worker = new SwingWorker<String, Object>() {
							@Override
							protected String doInBackground() throws Exception {
								EMAIL_MESSAGE = emailUtil.processAndSendEmail();
								return null;
							}
	
							@Override
							protected void done() {
									System.out.println("DONE " + EMAIL_MESSAGE);		
							}
						};
						worker.execute();
						System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
						
					 
				
			 }else{
				 System.out.println("FORM VALID ="+FORM_VALID);
			 }
			
		}
		
		public void validate(){
			 System.out.println("IN VALIDATE METHOD");
				FORM_VALID = true;		
				if(ValidationUtil.isEmpty(miscExpense.getApprovalComment(), "Approver Comments", null, FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
				}
				
		 }
		
		public void rejectMiscExpense(){
			System.out.println("IN REJECT");
			 validateReject();
			 if(FORM_VALID){
				
					 System.out.println("EXPENSES SIZE = "+miscExpensesDetails.size());
					
					
					 miscExpense.setExpenseStatus(CommonLookup.MISC_REJECT_STATUS);
					
					 miscReimbursementDAO.updateMiscExpenseForm(miscExpense);
					 FacesMessage msg = new FacesMessage("Miscellaneous reimbursement form is rejected.", null);  
				     FacesContext.getCurrentInstance().addMessage(null, msg);
				    // miscExpense = new MiscExpense();
				        Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);
						String domainName = context.getInitParameter("domainName");
						emailUtil = new EmailUtil();
						
						if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){
							String[] to = {miscExpense.getEmployee().getEmail()};//TO DO
							String[] cc = {accountant.getEmail()};
							emailUtil.setRecieverAddresses(to);
							emailUtil.setCCAddresses(cc);
						}else{
							String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
							emailUtil.setRecieverAddresses(to);
							emailUtil.setCCAddresses(to);
						}
						
						SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
						String messageString = "Dear "+miscExpense.getEmployee().getFirstName()+" "+miscExpense.getEmployee().getLastName()+",<br /><br />"+  
											
												"Your Miscellaneous Expense Request Form " + miscExpense.getMiscExpenseCode() + " is Rejected.<br /><br />" +
										        "<b>Approver comments : </b>"+miscExpense.getApprovalComment() +"<br />"+
										        "<br/>"+								
										        
										      
												"Thanks & Regards, <br />"+CommonLookup.WAM_DEVTEAM_SIGNATURE;;
						
						
						emailUtil.setMessage(messageString);
						emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
						emailUtil.setSubject("WAM - "+miscExpense.getEmployee().getFirstName()+ " "+miscExpense.getEmployee().getLastName()+" Misc. Expense Request (" + miscExpense.getMiscExpenseCode() + ") is Rejected");
	
						SwingWorker worker = new SwingWorker<String, Object>() {
							@Override
							protected String doInBackground() throws Exception {
								EMAIL_MESSAGE = emailUtil.processAndSendEmail();
								return null;
							}
	
							@Override
							protected void done() {
									System.out.println("DONE " + EMAIL_MESSAGE);		
							}
						};
						worker.execute();
						System.out.println( "BEFORE RETURNING: " + EMAIL_MESSAGE);
						
					 
				
			 }else{
				 System.out.println("FORM VALID ="+FORM_VALID);
			 }
			
		}

		public void validateReject(){
			 System.out.println("IN VALIDATE METHOD");
				FORM_VALID = true;		
				if(ValidationUtil.isEmpty(miscExpense.getApprovalComment(), "Approver Comments", null, FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
				}
				
				
						
				
		 }
	
		
		public MiscExpense getMiscExpense() {
			return miscExpense;
		}
		public void setMiscExpense(MiscExpense miscExpense) {
			this.miscExpense = miscExpense;
		}
	
		public Employee getEmployee() {
			return employee;
		}
	
		public void setEmployee(Employee employee) {
			this.employee = employee;
		}
	
		public MiscExpenseDetails getMiscExpenseDetails() {
			return miscExpenseDetails;
		}
	
		public void setMiscExpenseDetails(MiscExpenseDetails miscExpenseDetails) {
			this.miscExpenseDetails = miscExpenseDetails;
		}
	
		public List<MiscExpenseDetails> getMiscExpensesDetails() {
			return miscExpensesDetails;
		}
	
		public void setMiscExpensesDetails(List<MiscExpenseDetails> miscExpensesDetails) {
			this.miscExpensesDetails = miscExpensesDetails;
		}

		public Employee getAccountant() {
			return accountant;
		}

		public void setAccountant(Employee accountant) {
			this.accountant = accountant;
		}

		public float getBalance() {
			return balance;
		}

		public void setBalance(float balance) {
			this.balance = balance;
		}

		public List<Currency> getCurrencies() {
			return Currencies;
		}

		public void setCurrencies(List<Currency> currencies) {
			Currencies = currencies;
		}

		public List<LookupValue> getLookUpValuesList() {
			return lookUpValuesList;
		}

		public void setLookUpValuesList(List<LookupValue> lookUpValuesList) {
			this.lookUpValuesList = lookUpValuesList;
		}


		public TimeZone getTimeZone() {
			return timeZone;
		}


		public void setTimeZone(TimeZone timeZone) {
			this.timeZone = timeZone;
		}


		public Map<String,String> getCurrencyMap() {
			return currencyMap;
		}


		public void setCurrencyMap(Map<String,String> currencyMap) {
			this.currencyMap = currencyMap;
		}
		
	
	}
